import Pagination from '@/components/Pagination/index.vue'
import waves from '@/directive/waves'
import {createPermission, fetchParentList, fetchNodeList, deletePermission, updatePermission} from '@/api/permission'
import {parseTime} from '@/utils'

const calendarTypeOptions = [{key: 'CN', display_name: 'China'}, {key: 'US', display_name: 'USA'}, {
  key: 'JP', display_name: 'Japan'
}, {key: 'EU', display_name: 'Eurozone'}]

const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PermissionNode',

  components: {Pagination},

  directives: {waves}, filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success', 2: 'info', 0: 'danger'
      }
      return statusMap[status]
    }, typeFilter(type) {
      return calendarTypeKeyValue[type]
    }, statusText(status) {
      const statusMapText = {
        1: '正常', 2: '停用', 0: '已删除'
      }
      return statusMapText[status]
    }
  },

  data() {
    return {
      tableKey: 0,
      list: null,
      selectNodeId: [],
      PermissionParentList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1, limit: 20, importance: undefined, title: undefined, type: undefined, sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        api_route: '',
        controller: '',
        desc: '',
        functions: '',
        id: '',
        is_need_auth: '',
        is_system_menu: '',
        method: '',
        name: '',
        no: '',
        parentid: '',
        web_route: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑', create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        parentid: [{required: true, type: 'number', message: 'parentid 必填', trigger: 'change'}],
        name: [{required: true, message: 'name  必填', trigger: 'change'}],
        method: [{required: true, message: 'method 必填', trigger: 'blur'}]
      },
      downloadLoading: false,
      defaultProps: {
        children: 'children', label: 'label'
      }
    }
  },

  computed: {},

  watch: {},

  created() {
    this.getParentList()
    this.getNodeList('default')
  },

  methods: {
    getParentList() {
      this.listLoading = true
      fetchParentList(this.listQuery).then(response => {
        this.PermissionParentList = response.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    selectParent(checkNodes, checkKeys) {
      this.selectNodeId = []
      for (let i = 0; i < checkKeys.checkedNodes.length; i++) {
        if (checkKeys.checkedNodes[i].parentid > 0) {
          console.log(checkKeys.checkedNodes[i].parentid)
          this.selectNodeId.push(checkKeys.checkedNodes[i].id)
        }
      }
      if (this.selectNodeId.length > 0) {
        this.getNodeList('refresh')
      }
    },
    getNodeList(type) {
      let params = {}
      if (type === 'refresh') {
        params = {id: this.selectNodeId}
      } else {
        params = {parentid: 1}
      }
      fetchNodeList(params).then(response => {
        this.list = response.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功', type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {prop, order} = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        api_route: '',
        controller: '',
        desc: '',
        functions: '',
        id: '',
        is_need_auth: '',
        is_system_menu: '',
        method: '',
        name: '',
        no: '',
        parentid: '',
        web_route: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {

          createPermission(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功', message: '创建成功', type: 'success', duration: 2000
            })
            this.getParentList()
            if(this.selectNodeId.length>0){
              this.getNodeList('refresh')
            }else{
              this.getNodeList('default')
            }

          })
        }
      })
    },
    handleUpdate(row) {
      console.log(row)
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log(tempData)
          console.log(tempData.id)
          updatePermission(tempData.id, tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功', message: '更新成功', type: 'success', duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      deletePermission(row.id).then(() => {
        this.$notify({
          title: '成功', message: '删除成功', type: 'success', duration: 2000
        })
        this.getParentList()
        if(this.selectNodeId.length>0){
          this.getNodeList('refresh')
        }else{
          this.getNodeList('default')
        }
      })
    }
  }
}

